## This file is part of Invenio.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Function for archiving files"""

__revision__ = "$Id$"

from invenio.bibdocfile import \
     BibRecDocs, \
     decompose_file, \
     InvenioWebSubmitFileError, \
     CFG_WEBSUBMIT_DEFAULT_ICON_SUBFORMAT
import os
import re
from invenio.websubmit_icon_creator import create_icon
from invenio.websubmit_config import InvenioWebSubmitFunctionWarning
from invenio.websubmit_functions.Shared_Functions import get_dictionary_from_string, \
     createRelatedFormats
from invenio.errorlib import register_exception
from invenio.config import CFG_BINDIR
from invenio.dbquery import run_sql
from invenio.shellutils import run_shell_command

def Move_Files_to_Storage_Multi(parameters, curdir, form, user_info=None):
 
    global sysno, curdir_glob
    curdir_glob = curdir
    rename = parameters['rename']
    ## Create an instance of BibRecDocs for the current recid(sysno)
    bibrecdocs = BibRecDocs(sysno)
    ## Go through all the directories specified in the keys
    ## of parameters['paths_and_suffixes']
    counter = 0
    if os.path.exists(os.path.join(curdir, "files")):
            
        for path in os.listdir(os.path.join(curdir, "files")):
            counter += 1            
            ## Retrieve the restriction to apply to files in this
            ## directory
            ## Go through all the files in curdir/files/path
            for current_file in os.listdir(os.path.join(curdir, "files", path)):
                ## retrieve filename and extension
                dummy, filename, extension = decompose_file(current_file)
                if extension and extension[0] != ".":
                    extension = '.' + extension
                extension = "_{0}{1}".format(counter, extension)
                
                ## Build the new file name if rename parameter has been given
                if rename:
                    filename = re.sub('<PA>(?P<content>[^<]*)</PA>', \
                                      get_pa_tag_content, \
                                      parameters['rename'])

           			## Rename the file
                    try:
                        # Write the log rename_cmd
                        fd = open("%s/rename_cmd" % curdir, "a+")
                        fd.write("%s/files/%s/%s" % (curdir, path, current_file) + " to " +\
                                  "%s/files/%s/%s%s" % (curdir, path, filename, extension) + "\n\n")
                        ## Rename
                        os.rename("%s/files/%s/%s" % (curdir, path, current_file), \
                                  "%s/files/%s/%s%s" % (curdir, path, filename, extension))

                        fd.close()
                        ## Save the new name in a text file in curdir so that
                        ## the new filename can be used by templates to created the recmysl
                        fd = open("%s/%s_RENAMED" % (curdir, path), "w")
                        fd.write("%s%s" % (filename, extension))
                        fd.close()
                    except OSError, err:
                        msg = "Cannot rename the file.[%s]"
                        msg %= str(err)
                        raise InvenioWebSubmitFunctionWarning(msg)
                fullpath = "%s/files/%s/%s%s" % (curdir, path, filename, extension)
                ## Check if there is any existing similar file
                if not bibrecdocs.check_file_exists(fullpath):
                    bibdoc = bibrecdocs.add_new_file(fullpath, doctype=path, never_fail=True)
        # Update the MARC
        #bibdocfile_bin = os.path.join(CFG_BINDIR, 'bibdocfile --yes-i-know')
        #run_shell_command(bibdocfile_bin + " --fix-marc --recid=%s", (str(sysno),))

        # Delete the HB BibFormat cache in the DB, so that the fulltext
        # links do not point to possible dead files
        run_sql("DELETE from bibfmt WHERE format='HB' AND id_bibrec=%s", (sysno,))

def get_pa_tag_content(pa_content):
    """Get content for <PA>XXX</PA>.
    @param pa_content: MatchObject for <PA>(.*)</PA>.
    return: the content of the file possibly filtered by an regular expression
    if pa_content=file[re]:a_file => first line of file a_file matching re
    if pa_content=file*p[re]:a_file => all lines of file a_file, matching re,
    separated by - (dash) char.
    """
    pa_content = pa_content.groupdict()['content']
    sep = '-'
    out = ''
    if pa_content.startswith('file'):
        filename = ""
        regexp = ""
        if "[" in pa_content:
            split_index_start = pa_content.find("[")
            split_index_stop =  pa_content.rfind("]")
            regexp = pa_content[split_index_start+1:split_index_stop]
            filename = pa_content[split_index_stop+2:]## ]:
        else :
            filename = pa_content.split(":")[1]
        if os.path.exists(os.path.join(curdir_glob, filename)):
            fp = open(os.path.join(curdir_glob, filename), 'r')
            if pa_content[:5] == "file*":
                out = sep.join(map(lambda x: re.split(regexp, x.strip())[-1], fp.readlines()))
            else:
                out = re.split(regexp, fp.readline().strip())[-1]
            fp.close()
    return out

if __name__ == "__main__":
    sysno = 96323
    Move_Files_to_Storage_Multi({"rename" : "nusl-<PA>file:SN</PA>"}, "/home/invenio/websubmit_test", "")
